import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:test_flutter/constant/resources.dart';
import 'package:test_flutter/dio/Api.dart';
import 'package:test_flutter/dio/DioUtil.dart';
import 'package:test_flutter/model/scoped_model/main_model.dart';
import 'package:test_flutter/utils/ColorsUtil.dart';
import 'package:test_flutter/utils/TimerUtil.dart';
import 'package:test_flutter/utils/ToastUtil.dart';
import 'package:test_flutter/utils/common_utils/CustomLocalizations.dart';
import 'package:test_flutter/utils/factory/Fit.dart';
import 'package:test_flutter/widgets/Button.dart';
import 'package:test_flutter/widgets/EditText.dart';

class RegisterPage extends StatefulWidget {
  @override
  _Register createState() => new _Register();
}

class _Register extends State<RegisterPage> {
  TimerUtil timerCountDown;
  String tip = CustomLocalizations.instance
      .getString(StringIds.verificationCode);
  int stamp;
  bool canClick = true;


  @override
  Widget build(BuildContext context) {
    return  ScopedModelDescendant<MainModel>(
      builder: (context,child,model){
        return Theme(
            data: new ThemeData(
              primarySwatch: Colors.red,
              brightness: Brightness.light,
            ),
            child: new Scaffold(
              resizeToAvoidBottomPadding: true, //输入框抵住键盘
              backgroundColor: Colors.white,
              appBar: new AppBar(
                centerTitle: true,
                backgroundColor: ColorsUtil.Green,
                title: new Text(CustomLocalizations.instance.getString(StringIds.register)),
              ),
              body: new SingleChildScrollView(
                child: new Column(
                  children: <Widget>[
                    phoneNum,
                    new Stack(
                      alignment: new FractionalOffset(0.92, 0.5),
                      children: <Widget>[
                        verifyCode,
                        new GestureDetector(
                          onTap: canClick
                              ? () {
                            _setCodeTip();
                          }
                              : null,
                          child: Container(
                            width: Fit.scaleX(220),
                            height: Fit.scaleX(100),
                            padding: EdgeInsets.only(
                                left: Fit.scaleX(40),
                                top: Fit.scaleX(20),
                                right: Fit.scaleX(40),
                                bottom: Fit.scaleX(20)),
                            decoration: BoxDecoration(
                              borderRadius:
                              BorderRadius.circular(Fit.scaleX(15)),
                              color: ColorsUtil.Green,
                            ),
                            child: new Center(
                              child: Text(
                                tip,
                                style: new TextStyle(
                                    color: Colors.white,
                                    fontSize: Fit.scaleTextSize(44)),
                              ),
                            ),
                          ),
                        )
                      ],
                    ),
                    passWord,
                    new Padding(
                      padding: EdgeInsets.only(top: Fit.scaleY(200)),
                      child: new Button(CustomLocalizations.instance.getString(StringIds.register), onPressed: setOnclick),
                    )
                  ],
                ),
              ),
            )
        );;
      },
    );
  }

  void setOnclick() {
    register();
  }




  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    if (timerCountDown != null) timerCountDown.cancel(); //dispose()
  }

  /* 验证码获取*/
  void _setCodeTip() {

    if (phoneNum.getValue().length == 0) {
      ToastUtil.showToast(CustomLocalizations.instance.getString(StringIds.pleaseEnterUserName));
      return;
    }

    canClick = false;
    timerCountDown = new TimerUtil(mInterval: 1000, mTotalTime: 15 * 1000);
    timerCountDown.setOnTimerTickCallback((int value) {
      int tick = (value ~/ 1000);

      setState(() {

        if(tick == 0){
          canClick = true;
          tip = CustomLocalizations.instance
              .getString(StringIds.verificationCode);
        }else{
          print(tick);

          tip = tick.toString() + " s";
          canClick = false;
        }

        //(tick == 0) ? tip = '验证码' : tip = tick.toString() + " s";
      });
    });
    timerCountDown.startCountDown();

    getSmsVerificationCode();

  }

  /*UI 定义*/
  EditText phoneNum = new EditText(CustomLocalizations.instance
      .getString(StringIds.mobilePhoneNumber), 'images/phone.png');
  EditText verifyCode = new EditText(CustomLocalizations.instance
      .getString(StringIds.verificationCode), 'images/code.png');
  EditText passWord = new EditText(CustomLocalizations.instance
      .getString(StringIds.loginPassWord), 'images/password.png');



  ///注册接口
  register() async {

    if(verifyCode.getValue().length == 0){
      ToastUtil.showToast(CustomLocalizations.instance.getString(StringIds.PleaseGetCode));
      return;
    }

    if(passWord.getValue().length == 0){
      ToastUtil.showToast(CustomLocalizations.instance.getString(StringIds.pleaseEnterPassWord));
      return;
    }


    if(passWord.getValue().length < 6){
      ToastUtil.showToast(CustomLocalizations.instance.getString(StringIds.AtLeast6Bytes));
      return;
    }

    Map<String,String> requestMap = new Map();
    requestMap['VerificationCode'] = verifyCode.getValue();
    requestMap['TimeStamp'] = stamp.toString();
    requestMap['Password'] = passWord.getValue();
    requestMap['ConfirmPassword'] = passWord.getValue();
    requestMap['MobileNo'] = phoneNum.getValue();



    DioUtil.getInstance(context).post(
        Api.register,
            (response) {
          if (response.data['code'] == 1) {
            Navigator.of(context).pop();
          } else {
            ToastUtil.showToast(response.data['msg']);
          }
        },
        data: requestMap,
        errorCallBack: (errorMsg) {
          print("error:" + errorMsg);
          ToastUtil.showToast(errorMsg);
        });

  }
    ///获取验证码
  getSmsVerificationCode() async {
    DioUtil.getInstance(context).get(Api.getSmsVerificationCode + phoneNum.getValue(),
            (response) {
          if (response.data['code'] == 1) {
            stamp = response.data['data']['Stamp'];
            verifyCode.setValue(response.data['data']['VerifyCode']);
          } else {
            ToastUtil.showToast(response.data['msg']);
          }
        }, errorCallBack: (errorMsg) {
          print("error:" + errorMsg);
          ToastUtil.showToast(errorMsg);
        });


  }





}

